package com.zwj.gateway;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class IpRateLimiter {

    //每秒每IP最大请求数
    private static final int MAX_REQUESTS_PER_SECOND = 10;
    //过期时间 分钟
    private static final int EXPIRATION_TIME_MINUTES = 15;
    //最大缓存数量
    private static final int MAX_CACHE_SIZE = 30000;

    private static final Cache<String, RateLimiter> ipRateLimiterCache = Caffeine.newBuilder()
            .expireAfterWrite(EXPIRATION_TIME_MINUTES, TimeUnit.MINUTES)
            .expireAfterAccess(EXPIRATION_TIME_MINUTES, TimeUnit.MINUTES)
            .maximumSize(MAX_CACHE_SIZE)
            .build();

    public static boolean notAllowRequest(String ip) {
        RateLimiter rateLimiter = ipRateLimiterCache.get(ip, k -> RateLimiter.create(MAX_REQUESTS_PER_SECOND));
        return !rateLimiter.tryAcquire();
    }
}
